package com.wechat.core.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wechat.core.common.WeChatContant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * token 管理器
 *
 * @author hgb
 * @date 2019/1/26
 * Email xhy18650@sina.com
 */
public class TokenManager {

    private static Logger logger = LoggerFactory.getLogger(TokenManager.class);

    private static final String URL = "https://api.weixin.qq.com/cgi-bin/token";

    private static String token = null;

    private static Long lastGetAccessTokenTime = 0L; //上次获取access_token时间

    private static Long expires_in = 7100L; //微信token 过期未7200秒

    public static String getAccessToken() {
        Long currentTime = System.currentTimeMillis();
        if (token == null) {
            return refreshAccessToken();
        } else {
            if ((currentTime - lastGetAccessTokenTime )/ 1000 > expires_in) {
                return refreshAccessToken();
            }
        }
        return TokenManager.token;
    }


    public static String refreshAccessToken() {
        lastGetAccessTokenTime = System.currentTimeMillis();
        Map<String, Object> params = new HashMap<>();
        params.put("grant_type", "client_credential");
        params.put("appid", WeChatContant.appID);
        params.put("secret", WeChatContant.appsecret);
        try {
            String result = HttpClientUtils.httpGetRequest(URL, params);
            JSONObject jsonObject = JSON.parseObject(result);
            TokenManager.token = jsonObject.get("access_token").toString();
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("刷新token异常");
            return null;
        }
        return token;
    }

    public static void main(String[] args) {
        refreshAccessToken();
    }
}
